<template>
  <div class="main">
    <h4>{{ model == 'login' ? '欢迎登陆' : '用户注册' }}</h4>
    <el-form ref="ruleFormRef" label-position="right" label-width="80px" :rules="rules" :model="form" style="max-width: 460px">
      <el-form-item label="用户名" prop="username" required:any="true">
        <el-input type="text" v-model.trim="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" v-if="model !='login'" required:any="true">
        <el-input type="text" v-model.trim="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="密码" prop="password" required:any="true">
        <el-input type="password" v-model.trim="form.password" placeholder="请输入密码" show-password/>
      </el-form-item>
      <el-form-item label="确认密码" prop="repassword" v-if="model != 'login'" required:any="true">
        <el-input type="password" v-model.trim="form.repassword" placeholder="请再次输入密码" show-password />
      </el-form-item>
    </el-form>

    <el-form-item label-width="20px">
      <el-button type="primary" style="margin-left: 90px" @click="submitForm(ruleFormRef)">{{ model == 'login' ? '登陆' : '注册' }}</el-button>
      <el-button type="info" style="margin-left: 50px" @click="resetForm(ruleFormRef)">重置</el-button>
      <a @click.prevent="changeModel">{{ model == 'login' ? '没有密码？注册一个' : '去登陆' }}</a>
    </el-form-item>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import http from '../util/api'
import { useRouter } from 'vue-router'

const router = useRouter()

// 登录状态
const model=ref('login')

//表单内容
let form = ref({
  username: '',
  password: '',
  repassword: '',
  email: ''
})

const ruleFormRef = ref<FormInstance>()

// onMounted(() => {
//   console.log(process.env.VUE_APP_API);
// })

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//自定义确认密码验证规则
const checkRePsw = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码！'))
  } else if (value != form.value.password) {
    callback(new Error('两次输入的密码不一致！'))
  } else {
    callback()
  }
}

//自定义邮箱验证规则
const checkEmail = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入邮箱！'))
  } else if (!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(value))) {
    callback(new Error('请输入正确格式的邮箱！'))
  } else {
    callback()
  }
}


//表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '用户名不能为空！', trigger: 'blur' },
    { min: 4, max: 8, message: '请输入4~8位用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { min: 6, max: 12, message: '请输入6~12位密码！', trigger: 'blur' },
  ],
  repassword: [
    { required: true, validator: checkRePsw, trigger: 'blur' },
  ],
  email: [
    { required: true, validator: checkEmail, trigger: 'blur' },
  ],
})


//切换注册登陆
const changeModel = () => {
  model.value = model.value == 'login' ? 'register' : 'login'
  resetForm(ruleFormRef.value)
}

//表单提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (!valid) {
      console.log('error submit!')
      return false
    }

    if (model.value === 'login') {
      //登陆
      console.log('login!')

      http(`/register?username=${form.value.username}&password=${form.value.password}`).then((res) => {
        console.log(res);
        let { data } = res
        if (data.length != 0) {
          ElMessage({
            message: '登陆成功！',
            type: 'success',
          })
          resetForm(ruleFormRef.value)

          let obj = {
            id: data[0].id,
            username: data[0].username,
            power: data[0].power
          }
          localStorage.setItem('user', JSON.stringify(obj))
          router.push('/index')
        } else {
          ElMessage({
            message: '用户名或密码错误！',
            type: 'error',
          })
        }
      })
    } else {
      //注册
      let data = {
        "username": form.value.username,
        "password": form.value.password,
        "email": form.value.email,
        "power": []
      }
      http('/register', "POST", data).then((res) => {
        console.log(res);
        let { data } = res
        if (Object.keys(data).length != 0) {
          ElMessage({
            message: '注册成功！',
            type: 'success',
          })
          changeModel()
        } else {
          ElMessage({
            message: '注册失败！',
            type: 'error',
          })
        }
      })
    }

  })



}
</script>

<style lang="scss" scoped>
.main {
  border: 1px solid #eee;
  margin: 100px auto;
  width: 500px;
  text-align: center;
  a {
        position: absolute;
        right: 50px;
        text-decoration: underline;
        color: #409eff;
        cursor: pointer;
    }
}
</style>

